package com.example.testapplication;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.Nullable;

public class SpActivity extends ApplicationActivity{
    private EditText et_sp_key;
    private EditText et_sp_value;

    private SharedPreferences sp;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sp);

        et_sp_key = (EditText) findViewById(R.id.et_sp_key);
        et_sp_value = (EditText) findViewById(R.id.et_sp_value);

        // 第一步 得到sp对象 atguigu.xml
        sp = getSharedPreferences("atguigu", Context.MODE_PRIVATE);


    }

    public void save(View view){
        // 第二步的到editor对象
        Editor editor = sp.edit();
        // 3.得到输入的key/value
        String key = et_sp_key.getText().toString();
        String value = et_sp_value.getText().toString();
        // 4.使用editor保存key-value
        editor.putString(key,value).commit();
        //5.提示
        Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();

    }

    public void read(View view){
        // 1.得到输入key
        String key = et_sp_key.getText().toString();
        //2.根据key读取对应的value
        String value = sp.getString(key,null);
        // 3. 显示
        if(value == null){
            Toast.makeText(this, "没有找到对应的value", Toast.LENGTH_SHORT).show();
        }else{
            et_sp_value.setText(value);
        }


    }
}
